package com.lyf.activemq.simple;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/6
 * @VERSION 1.0
 * @DESC
 */
public class JmsConsumerDemo {
    public static final String ACTIVE_URL = "tcp://47.98.99.88:61616";
    public static final String QUEUE_NAME = "queue-1";

    public static void main(String[] args) throws JMSException, IOException {
        // ActiveMQConnectionFactory'
        //创建连接工厂，并开启连接
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
        Connection connection =  activeMQConnectionFactory.createConnection();
        connection.start();

        // 开启session会话
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        // 创建目的地（队列OR主题）
        Queue queue = session.createQueue(QUEUE_NAME);
        //
        MessageConsumer messageConsumer = session.createConsumer(queue);

        //messageConsumer.receive();
        // 法一:receive:同步阻塞办法
//        while (true){
//           TextMessage message=(TextMessage) messageConsumer.receive();
//           if(null!=message){
//               System.out.println("收到消息:"+message.getText());
//           }else {
//               break;
//           }
//        }
//        messageConsumer.close();
//        session.close();
//        connection.close();

        // 法二:监听的方式

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if(message!=null&& message instanceof TextMessage){
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.in.read();//保持控制台不灭
        messageConsumer.close();
        session.close();
        connection.close();


    }
}
